package accs.gui;

import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URI;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

import accs.gui.logic.CheckerTask;
import accs.model.AccountChecker;
import accs.model.ebay.EbayChecker;
import accs.model.facebook.FacebookChecker;
import accs.model.fileover.FileoverChecker;
import accs.model.mail.MailAccountChecker;
import accs.model.minecraft.MinecraftChecker;
import accs.model.otheraccessories.Formatter;
import accs.model.packstation.PackstationChecker;
import accs.model.paypal.PayPalChecker;
import accs.model.proxy.CheckProxy;
import accs.model.staemme.DieStaemmeAccountChecker;
import accs.model.steam.SteamChecker;
import accs.model.uploaded.UploadedChecker;
import accs.model.zalando.ZalandoChecker;
import accs.product.license.License;

/**
 * Mainframe of the account checker application.
 * @author syxolk
 */
public class MainFrame extends JFrame {

	private JPanel contentPane;
	private Box listPanel;

	/**
	 * Create the frame.
	 */
	public MainFrame() {
		setIconImage(Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource("/accs/gui/img/icon.png")));
		setTitle("Hermes - AccountChecker");
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setSize(450, 300);
		setLocationRelativeTo(null);
		
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				exit();
			}
		});
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu mnTask = new JMenu("Task");
		menuBar.add(mnTask);
		
		JMenu mnNewMenu = new JMenu("New AccountChecker");
		initAccountCheckerMenu(mnNewMenu);
		mnTask.add(mnNewMenu);
		
		JMenuItem mntmCloseAllTasks = new JMenuItem("New ProxyChecker");
		mntmCloseAllTasks.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				newAccountCheckerTask(new CheckProxy(),false);
			}
		});
		mnTask.add(mntmCloseAllTasks);
		
		JMenuItem mntmFormatter = new JMenuItem("New Formatter");
		mntmFormatter.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				newAccountCheckerTask(new Formatter(),false);
			}
		});
		mnTask.add(mntmFormatter);
		
		JMenuItem mntmNewMailcracker = new JMenuItem("New MailCracker");
		mntmNewMailcracker.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				newMailCracker();
			}
		});
		mnTask.add(mntmNewMailcracker);
		
		JMenuItem mntmNewMailchecker = new JMenuItem("New MailChecker");
		mntmNewMailchecker.setEnabled(false);
		mnTask.add(mntmNewMailchecker);
		
		JMenuItem mntmNewEbayutils = new JMenuItem("New EbayUtils (userid -> mail)");
		mntmNewEbayutils.setEnabled(false);
		mnTask.add(mntmNewEbayutils);
		
		mnTask.addSeparator();
		
		JMenuItem mntmExit = new JMenuItem("Exit");
		mntmExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				exit();
			}
		});
		mnTask.add(mntmExit);
		
		JMenu mnHelp = new JMenu("Product");
		menuBar.add(mnHelp);
		
		JMenuItem mntmHelp = new JMenuItem("License");
		mntmHelp.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				showLicense();
			}
		});
		
		JMenuItem mntmHelp_1 = new JMenuItem("Help...");
		mntmHelp_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				showHelp();
			}
		});
		mnHelp.add(mntmHelp_1);
		mnHelp.add(mntmHelp);
		
		JMenuItem mntmAbout = new JMenuItem("About");
		mntmAbout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				showAbout();
			}
		});
		mnHelp.add(mntmAbout);
		
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		JScrollPane scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		contentPane.add(scrollPane, BorderLayout.CENTER);
		
		listPanel = new Box(BoxLayout.Y_AXIS);
		scrollPane.setViewportView(listPanel);
		
		//for(int i=0; i<5; i++) listPanel.add(new TaskPanel());
		listPanel.add(Box.createVerticalGlue());
		//listPanel.add(Box.createVerticalStrut(0));
	}
	
	/**
	 * List of account checkers.
	 */
	private static final AccountChecker[] ACCOUNT_CHECKER=new AccountChecker[]{new MailAccountChecker(),new PayPalChecker(),new PackstationChecker(),new ZalandoChecker(),new EbayChecker(),new UploadedChecker(),new FileoverChecker(), new FacebookChecker(),new SteamChecker(),new MinecraftChecker(),new DieStaemmeAccountChecker()};
	
	/**
	 * Initialize the account checker menu.
	 * @param menu menu where menu items are inserted
	 */
	private void initAccountCheckerMenu(JMenu menu) {
		for(int i=0; i<ACCOUNT_CHECKER.length; i++) {
			AccountChecker checker=ACCOUNT_CHECKER[i];
			
			JMenuItem item=new JMenuItem(new ImageIcon(checker.getImage()));
			item.setEnabled(License.getInstance().checkPermission(checker));
			item.setActionCommand(String.valueOf(i));
			item.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					newAccountCheckerTask(ACCOUNT_CHECKER[Integer.parseInt(e.getActionCommand())],true);
				}
			});
			
			menu.add(item);
		}
	}
	
	/**
	 * Interactive close method for the application.
	 */
	private void exit() {
		int res=JOptionPane.showConfirmDialog(this,"Do you really want to close the program?","Exit",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
		if(res==JOptionPane.YES_OPTION) {
			System.exit(0);
		}
	}
	
	/**
	 * Dialog cache for the account checker.
	 */
	private AccountCheckerDialog dlg=new AccountCheckerDialog(this);
	
	/**
	 * Adds a new account checker task to the gui.
	 * @param checker Object of the account checker
	 */
	private void newAccountCheckerTask(final AccountChecker checker, boolean checkPermissions) {
		if(checkPermissions && !License.getInstance().checkPermission(checker)) {
			JOptionPane.showMessageDialog(this,"You don't have the permission to create this task!","Permission denied",JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				dlg.setAccountChecker(checker);
				dlg.setVisible(true);
				
				CheckerTask task=dlg.getTask();
				
				if(task!=null) {
					listPanel.add(new TaskPanel(task),listPanel.getComponentCount()-1);
					listPanel.validate();
				}
			}
		});
	}
	
	private void newMailCracker() {		
		MailCrackerDialog dlg=new MailCrackerDialog(this);
		dlg.setVisible(true);
		
		if(dlg.getResult()) {
			try {
				CheckerTask task=dlg.getTask();
				listPanel.add(new TaskPanel(task),listPanel.getComponentCount()-1);
				listPanel.validate();
			} catch (Exception e) {
				JOptionPane.showMessageDialog(MainFrame.this,e.toString(),"Error",JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	
	private void showAbout() {
		new AboutDialog(this).setVisible(true);
	}
	
	private void showLicense() {
		new LicenseDialog(this).setVisible(true);
	}
	
	private static final String HELP_URL="/checker";
	
	private void showHelp() {
		boolean success=false;
		
		try {
			if(Desktop.isDesktopSupported()) {
				Desktop.getDesktop().browse(new URI(HELP_URL));
				success=true;
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		if(!success) JOptionPane.showMessageDialog(this,"Error during opening the page. Please open the page on your own: "+HELP_URL,"Error",JOptionPane.ERROR_MESSAGE);
	}
}